package com.qf.blog.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//// 只拦截动态资源
//@WebFilter(filterName = "EncodingFilter", urlPatterns = {
//        "/SystemUserServlet/*","/PageServlet/*","/IndexServlet/*","/UserServlet/*"})
//public class EncodingFilter implements Filter {
//
//    private String encoding = "utf-8";
//
//    @Override
//    public void init(FilterConfig filterConfig) throws ServletException {
//
//    }
//
//    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
//        // 1.类型转换
//        HttpServletRequest req = (HttpServletRequest) request;
//        HttpServletResponse resp = (HttpServletResponse) response;
//
//        // 2.设置编码
//        req.setCharacterEncoding(encoding); // 读取内容的时候使用utf-8去读
////        resp.setContentType("text/html;charset=" + encoding);
//            // 设置响应的内容编码
//        resp.setCharacterEncoding("utf-8");
//
//        // 3、放行
//        chain.doFilter(req, resp);
//    }
//
//    @Override
//    public void destroy() {
//    }

// 只拦截动态资源
@WebFilter(filterName = "EncodingFilter", urlPatterns = {
        "/SystemUserServlet/*","/PageServlet/*",
        "/IndexServlet/*","/UserServlet/*",
        "/static/static/discuss-publish.html",
        "/invitataionServlet/*",
        "/commentServlet/*"
})
public class EncodingFilter implements Filter {

    private String encoding = "utf-8";

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 1.类型转换
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        // 2.设置编码
        req.setCharacterEncoding(encoding); // 读取内容的时候使用utf-8去读
//        resp.setContentType("text/html;charset=" + encoding); // 设置响应的内容编码
        resp.setCharacterEncoding("utf-8");

        // 3、放行
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
    }

    public void init(FilterConfig config) throws ServletException {
    }
}
